package cn.itcast.demo.web;

import cn.itcast.demo.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;

/**
 * @author 虎哥
 */
@Slf4j
@RestController
@RequestMapping("hello")
public class HelloController {

    @GetMapping("sync")
    public User getUser(){
        log.info("sync准备开始查询");
        User user = createUser();
        log.info("sync查询结束，返回结果");
        return user;
    }

    @GetMapping("async")
    public Mono<User> getUserAsync(){
        log.info("async准备开始查询");
        Mono<User> mono = Mono.fromSupplier(this::createUser);
        log.info("async查询结束，返回结果");
        return mono;
    }

    @GetMapping("flux")
    public Flux<User> getUserFlux(){
        log.info("flux准备开始查询");
        Flux<User> userFlux = createUserFlux();
        log.info("flux查询结束，返回结果");
        return userFlux;
    }

    @GetMapping(value = "stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<User> getUserFluxStream(){
        log.info("flux准备开始查询");
        Flux<User> userFlux = createUserFlux();
        log.info("flux查询结束，返回结果");
        return userFlux;
    }

    private Flux<User> createUserFlux(){
        return Flux // 每隔一秒，发射一个数据，默认是发射long，从0开始递增
                .interval(Duration.ofSeconds(1))
                // 把long转int
                .map(Long::intValue)
                // 把int封装到user
                .map(i -> User.of("user_" + i, 20 + i))
                // 取前3个user
                /*.take(3)*/;
    }

    private User createUser(){
        try {
            // 模拟业务耗时1秒
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return User.of("Rose", 18);
    }
}
